<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Delete Nested JSON Object by ID</title>
</head>
<body>
    <script>
        // 递归删除函数
        function deleteById(obj, targetId) {
            for (let key in obj) {
                if (obj.hasOwnProperty(key)) {
                    if (typeof obj[key] === 'object' && obj[key] !== null) {
                        // 递归处理嵌套对象
                        deleteById(obj[key], targetId);

                        // 如果嵌套对象被清空，删除父对象的键
                        if (Object.keys(obj[key]).length === 0) {
                            delete obj[key];
                        }
                    } else if (key === 'id' && obj[key] === targetId) {
                        // 如果当前对象是目标对象，删除它
                        delete obj[key];
                    }
                }
            }
        }

        // 原始 JSON 对象
        let json = {
            "a": { "id": 1, "name": "Apple" },
            "b": { "id": 2, "name": "Banana", "nested": { "id": 2, "name": "Yellow Banana" } },
            "c": { "id": 3, "name": "Orange" }
        };

        // 要删除的子对象的 id
        let targetId = 2;

        // 删除符合条件的子对象
        deleteById(json, targetId);

        // 输出结果
        console.log(json);
    </script>
</body>
</html>